import axios from "axios";
import { Message, Loading } from "element-ui";
import config from "./config";
import Vue from "vue";
import _ from "lodash";

// loading框设置局部刷新，且所有请求完成后关闭loading框
let loadingInstance; //loading 实例
let needLoadingRequestCount = 0; //当前正在请求的数量

function showLoading() {
  let main = document.querySelector("#app"); //获取dom节点
  if (main) {
    if (needLoadingRequestCount === 0 && !loadingInstance) {
      loadingInstance = Loading.service({
        target: main,
        text: "正在加载...",
        background: "rgba(0,0,0,0.5)",
        spinner: "el-icon-loading"
      });
    }
    needLoadingRequestCount++;
  }
}
function closeLoading() {
  Vue.nextTick(() => {
    // 以服务的方式调用的 Loading 需要异步关闭
    needLoadingRequestCount--;
    needLoadingRequestCount = Math.max(needLoadingRequestCount, 0); // 保证大于等于0
    if (needLoadingRequestCount === 0) {
      if (loadingInstance) {
        hideLoading();
      }
    }
  });
}
//防抖
var hideLoading = _.debounce(() => {
  loadingInstance.close();
  loadingInstance = null;
}, 10);

// create an axios instance
const service = axios.create({
  baseURL: "",
  timeout: 15000
});
// request interceptor
service.interceptors.request.use(
  config => {
    config["Content-Type"] = "application/json";
    config.headers["Authorization"] =
      "Bearer eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJuZXVzb2Z0IiwiaWF0IjoxNjIzNjYzMzk4LCJleHAiOjE2Mjk2NjMzOTgsImFjY2Vzc190b2tlbiI6IjJiMmI3ZmYyLTgxNzktNGYxMi1iZjQ5LTQzMTQ4YzFiMWVjNiIsInJlZnJlc2hfdG9rZW4iOiI4MzAyMDMwYi1lM2Y5LTRhMDQtYWI2Ni0xYmEzOGRjNjE1ZTgiLCJ1c2VySWQiOiIyMTI1NSIsIkV4cGlyZXNfaW4iOjYwMDAwMDB9.A0q8JHGgVLW7A38M7aVVTU3IyPGsiqJNpt4r1vc0SxY23wXTFbd_pXOpSDvuwLasN1DnjokOsJQICIUtSi3NWWJNApq2EYqf5v-UxHwedGmHxcwflxZWjI-coDNP9UVgGsHndaRV2Xfg027vVfh1FsaP3tvKNGSD-jX7eBs6ZxM";
    showLoading(); // 开始加载loading
    return config;
  },
  error => {
    closeLoading();
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  response => {
    closeLoading(); // 结束加载loading
    const res = response.data;
    if (res.code != 200) {
      Message({
        message: res.msg || "Error",
        type: "error"
      });
      return Promise.reject(new Error(res.msg || "Error"));
    } else return res;
  },
  error => {
    closeLoading();
    Message({
      message: "服务内部错误，请联系技术人员！",
      type: "error"
    });
    return Promise.reject(error);
  }
);

/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function get(url, params) {
  return new Promise((resolve, reject) => {
    axios
      .get(url, {
        params: params
      })
      .then(res => {
        resolve(res.data);
      })
      .catch(err => {
        reject(err.data);
      });
  });
}
/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function post(url, params) {
  return new Promise((resolve, reject) => {
    axios
      .post(url, QS.stringify(params))
      .then(res => {
        resolve(res.data);
      })
      .catch(err => {
        reject(err.data);
      });
  });
}

// getPermissions(url, params) {
//   var instance = axios.create({
//     baseURL: config.base.ip
//   })
//   instance.defaults.headers.Authorization = 'Bearer ' + getToken()
//   return new Promise((resolve, reject) => {
//     instance.get(url, {
//         'params': params
//       })
//       .then(response => {
//         resolve(response.data)
//       }, err => {
//         Message({
//           message: err.message,
//           type: 'error',
//           duration: 5 * 1000
//         })
//         reject(err)
//       })
//       .catch((error) => {
//         reject(error)
//       })
//   })
// }

export default service;
